import axios from "axios";
import { getToken, removeToken, removePerson } from 'utils/auth' // 验权
import { Message, MessageBox } from 'element-ui'
import LoginModal from 'src/components/user/LoginModal'

import i18n from 'src/i18n'

const Axios = axios.create({
    baseURL: "https://www.lunzi.online", 
    timeout: 10000,
    responseType: "json",
    // withCredentials: true, // 是否允许发送和接收cookie
    headers: {
        "Content-Type": "application/json;charset=UTF-8"
    }
});

const BASEURLS = {
    'liuhaojie': 'https://www.lunzi.online',
    'da': 'http://47.96.24.53:80/t/'
}

//POST传参序列化(添加请求拦截器)
Axios.interceptors.request.use(
    config => {
        // 在发送请求之前
        // console.log(config)

        let params;
        if (config.data){
            params = config.data;
        }
        if (config.params){
            params = config.params;
        }

        // 根据参数判断请求host
        if (config.baseURL === "" && config.url.indexOf("http") === -1){

            config.url = BASEURLS[(params.host || config.host)] + config.url;
        }

        return config;
    },
    error => {

        return Promise.reject(error);
    }
);

//返回状态判断(添加响应拦截器)
Axios.interceptors.response.use(
    res => {
        // console.log(res.headers)
        /**
         * code为非0是抛错 
         */
        if (res && res.data && res.data.code !== undefined && res.data.code !== 0) {

            if (res.data.code === 4005 || res.data.code === 4006){

                removeToken();
                removePerson();

                MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
                    confirmButtonText: '重新登录',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    location.href = "user.html#/login";
                })

                return;   
            }

            Message({
                message: res.data.dialog && res.data.dialog.content || i18n.t('layout.netError'),
                type: 'error',
                duration: 5 * 1000
            })

            return Promise.reject(res)
        } else {
            return res || new Object()
        }
    },
    error => {
        // console.log(JSON.stringify(error))
        let errResponse = error.response || {};

        if (errResponse && errResponse.data && (errResponse.data.code === 4005 || errResponse.data.code === 4006)){

            removeToken();
            removePerson();

            MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
                confirmButtonText: '重新登录',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                location.href = "user.html#/login";
            })

            return;   
        } 

        Message({
            message: errResponse && errResponse.data && errResponse.data.msg || i18n.t('layout.netError'),
            type: 'error',
            duration: 5 * 1000
        })

        return Promise.reject(error);
    }
);


export default {
    // 对axios的实例重新封装成一个plugin ,方便 Vue.use(xxxx)
    install(Vue, Option) {
        Object.defineProperty(Vue.prototype, "$http", { value: Axios });
    },
    //Post  请求方式
    post(url, params = {}, config = {}) {
        return new Promise((resolve, reject) => {
            Axios.post(url, params, config).then(response => {
                resolve(response.data);
            }, err => {
                reject(err);
            })
            .catch((error) => {
                reject(error)
            })
        })
    },

    //GET 请求方式
    get(url, params = {}) {
        return new Promise((resolve, reject) => {
            Axios.get(url, { params: params}).then(response => {
                resolve(response.data);
            }, err => {
                reject(err);
            })
            .catch((error) => {
                reject(error)
            });
        })

    },

    patch(url, params = {}){
        return new Promise((resolve,reject) => {
            Axios.patch(url, params).then(response => {
                resolve(response.data);
            },err => {
                reject(err)
            })
            .catch((error) => {
                reject(error)
            });
        })
    },

    put(url, params = {}) {
        return new Promise((resolve, reject) => {
            Axios.put(url, { params: params}).then(response => {
                resolve(response.data);
            }, err => {
                reject(err);
            })
            .catch((error) => {
                reject(error)
            });
        })

    }
}
